<template>
  <div class="addDoctor">
    <div class="ele-title"><h4 v-if="id">编辑医生</h4><h4 v-else>添加医生</h4></div>
    <div class="ele-con-res"><span>医生信息</span></div>
    <div class="ele-content">
      <el-form ref="doctorForm" :model="form" :rules="ruleDoctor" label-position="left" label-width="130px">
        <el-form-item label="医生名称:" prop="doctorName">
          <el-col :span="6">
            <el-input v-model="form.doctorName" placeholder="请输入医生名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="手机号码:" prop="phone">
          <el-col :span="6">
            <el-input v-model="form.phone" placeholder="请输入手机号码" />
          </el-col>
        </el-form-item>
        <el-form-item label="医院:" prop="hospital">
          <el-col :span="6">
            <el-input v-model="form.hospital" placeholder="请输入医院" />
          </el-col>
        </el-form-item>
        <el-form-item label="服务科室:" prop="department">
          <el-col :span="6">
            <el-cascader
              v-model="form.department"
              placeholder="服务科室"
              class="ele-cascader"
              :show-all-levels="false"
              :options="departmentOptions"
              clearable
              @change="serviceList=[]"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="服务城市:" prop="serviceCity">
          <el-col :span="6">
            <el-cascader
              v-model="form.serviceCity"
              class="ele-cascader"
              :show-all-levels="false"
              :options="serviceCityOptions"
              clearable
              @change="serviceList=[]"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="提供服务:" required>
          <el-col :span="6">
            <el-row class="service-head">
              <el-col :span="18">
                <span>服务名称</span>
              </el-col>
              <el-col :span="6">
                <span>操作</span>
              </el-col>
            </el-row>
            <el-row v-for="(item,index) in serviceList" :key="index">
              <el-col :span="18">
                <span hidden>{{ item.onlineCityId }}</span>
                <span>{{ item.name }}</span>
              </el-col>
              <el-col :span="6">
                <el-button type="text" class="el-button-delete" @click="deleteService(index)">删除</el-button>
              </el-col>
            </el-row>
            <el-button type="text" @click="addServiceList">添加服务</el-button>
          </el-col>
        </el-form-item>

        <!--        <el-form-item label="服务时间段:" >
          <el-col :span="22">
            <el-col :span="6">
              <el-input v-model="timeModel.templateName" placeholder="选择模板" @focus="selectModel" />
              <el-input v-model="form.timeModel" type="hidden" />
            </el-col>
            <el-col :span="2" class="el-col-offset-2">
              <el-button type="text" @click="addModel">添加模板</el-button>
            </el-col>
            <el-col v-show="form.timeModel" :span="24" class="timeModelBox">
              <el-form :model="timeModel">
                <el-form-item label="可预约时间:">
                  <el-col :span="6">
                    <el-input v-model="timeModel.appointmentDay" :disabled="true"/>
                  </el-col>
                  <el-col :span="2">天</el-col>
                  <el-col :span="20">
                    <p class="title-txt">用户可预约的最长天数，租赁商品的附加规格从用户收货后开始计算。</p>
                  </el-col>
                </el-form-item>
                <div v-for="(item,index) in timeModel.serviceTime" :key="index">
                  <DoctorTimeInterval ref="DoctorTimeInterval" :index="index" :disabled="true" :time-form="item" @delete="deleteTimeInterval" />
                </div>

              </el-form>
            </el-col>
          </el-col>
        </el-form-item>-->
        <div class="ele-con-res" style="margin-bottom: 22px"><span>群设置</span></div>
        <!--        <div class="ele-title" >
          <span>群设置</span>
        </div>-->
        <el-form-item label="群聊名称:" prop="groupName">
          <el-col :span="5">
            <el-input
              v-model="form.groupName"
              maxlength="50"
              placeholder="请输入群聊名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="24">
            <el-alert
              title="最多50个utf8字符，超过将截断。"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="群主ID:" prop="groupManager">
          <el-col :span="5">
            <el-input
              v-model="form.groupManager"
              maxlength="20"
              placeholder="请输入群主ID"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="员工企业微信ID:" prop="staffWechatName">
          <el-col :span="5">
            <el-input
              v-model="form.staffWechatName"
              maxlength="32"
              placeholder="请输入员工企业微信ID"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="群成员ID:" prop="groupMembers">
          <el-col :span="5">
            <el-input
              v-model="form.groupMembers"
              placeholder="请输入群成员ID"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="24">
            <el-alert
              title="群成员id列表,至少2人，至多2000人。"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDoctor">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 选择服务 -->
    <el-dialog :visible.sync="dialogVisibleService" width="60%">
      <div slot="title" class="ele-dialog-title">选择服务</div>
      <div class="ele-div-keysearch">
        <div class="search-left search-flex" />
        <div class="search-right search-flex">
          <div class="ele-input">
            <el-input v-model="keywords" suffix-icon="el-icon-search" placeholder="输入名称搜索" />
          </div>
          <el-button type="primary" @click="getServiceList">确定</el-button>
          <el-button type="infor" @click="appendOnlineService">添加服务</el-button>
          <el-button type="infor" @click="resetService">刷新</el-button>
        </div>
      </div>
      <div class="ele-table">
        <el-table :data="list" stripe>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="可预约时间" prop="appointmentDay" />
          <el-table-column label="服务时间段" prop="serviceTime">
            <template slot-scope="scope">
              <div v-for="(item,index) in JSON.parse(scope.row.serviceTime)" :key="index">
                <p>{{ item.startTime }}-{{ item.endTime }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                plain
                @click="selectService(scope.row)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="ele-div-footer">
          <div class="footer-left" />
          <el-pagination
            class="pagination-right"
            :current-page="pages.currentPage"
            :page-sizes="pages.pageSizes"
            :page-size="pages.pageSize"
            :total="pages.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>
    <!-- 选择模板 -->
    <!--    <el-dialog :visible.sync="dialogVisibleModel" width="80%">
      <div slot="title" class="ele-dialog-title">选择模板</div>
      <div class="ele-div-keysearch">
        <div class="search-left search-flex" />
        <div class="search-right search-flex">
          <div class="ele-input">
            <el-input v-model="keywords" suffix-icon="el-icon-search" placeholder="输入名称搜索" />
          </div>
          <el-button type="primary" @click="getTimeModelList">确定</el-button>
          <el-button type="infor" @click="addModel">添加模板</el-button>
          <el-button type="infor" @click="getTimeModelList">刷新</el-button>
        </div>
      </div>
      <div class="ele-table">
        <el-table :data="list" stripe>
          <el-table-column label="模板名称" prop="templateName" />
          <el-table-column label="可预约时间" prop="appointmentDay">
            <template slot-scope="scope">
              {{ scope.row.appointmentDay }}天
            </template>
          </el-table-column>
          <el-table-column label="服务时间段" prop="serviceTime">
            <template slot-scope="scope">
              <div v-for="(item,index) in JSON.parse(scope.row.serviceTime)" :key="index">
                <p>{{ item.startTime }}-{{ item.endTime }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                plain
                @click="selectModelTime(scope.row)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="ele-div-footer">
          <div class="footer-left" />
          <el-pagination
            class="pagination-right"
            :current-page="pages.currentPage"
            :page-sizes="pages.pageSizes"
            :page-size="pages.pageSize"
            :total="pages.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
/* import DoctorTimeInterval from '@/views/service/component/DoctorTimeInterval'*/
import { addDoctor, departmentList, getServiceByCityId } from '@/api/service'
import { getShopID } from '@/utils/auth'
import { getTwoLevelCityList } from '@/api/auth'
import validate from '@/utils/formValidate'
import { Loading } from 'element-ui'
export default {
  name: 'AddDoctor',
  /* components: { DoctorTimeInterval },*/
  data() {
    return {
      id: '',
      isEditDotcor: false,
      form: {
        doctorName: '',
        phone: '',
        hospital: '',
        department: '',
        serviceCity: '',
        serviceList: [],
        timeModel: '',
        groupName: '',
        groupManager: '',
        staffWechatName: '',
        groupMembers: '',
        wechatGroupId: ''
      }, // form表单
      departmentOptions: [], // 科室options
      pages: {
        pageSizes: [10, 20, 30, 40],
        pageSize: 10,
        currentPage: 1,
        total: 0
      }, // dialog分页

      serviceCityOptions: [], // 服务城市options
      list: [], // dialog模板列表

      loadServiceList: [], // dialog服务列表
      modal: true,

      keywords: '', // dialog 关键词

      serviceList: [], // dialog选择完的服务列表

      dialogVisibleService: false, // 服务dialog状态

      dialogVisibleModel: false, // 模板dialog状态
      timeform: {
        day: ''
      }, // 时间模板详情
      timeModel: {
        id: '',
        templateName: '',
        appointmentDay: '',
        serviceTime: []
      }, // 时间模板
      ruleDoctor: {
        doctorName: [
          { required: true, message: '医生名称不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '医生手机不能为空', trigger: 'blur' },
          { required: true, validate: validate.validatePhone, trigger: 'blur' }
        ],
        hospital: [
          { required: true, message: '医院不能为空', trigger: 'blur' }
        ],
        department: [
          { required: true, message: '科室不能为空', trigger: ['change', 'blur'] }
        ],
        serviceCity: [
          { required: true, message: '服务城市不能为空', trigger: ['change', 'blur'] }
        ],
        groupName: [{ required: true, message: '请输入群聊名称', trigger: 'blur' }],
        groupManager: [
          { required: true, message: '请输入群主id', trigger: 'blur' },
          {
            validator: validate.isCompanyWeChat,
            trigger: ['change', 'blur']
          }
        ],
        staffWechatName: [
          { required: true, message: '请输入员工企业微信id', trigger: 'blur' },
          {
            validator: validate.isCompanyWeChat,
            trigger: ['change', 'blur']
          }
        ],
        groupMembers: [
          { required: true, message: '请输入群成员id', trigger: 'blur' },
          {
            validator: validate.isChar,
            trigger: ['change', 'blur']
          }
        ]
      }
    }
  },
  watch: {
    'form.serviceCity': {
      handler(newValue, oldValue) {
        this.form.serviceList = []
        this.serviceList = []
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      const params = this.$dd(this.$route.query.p)
      if (params && params.edit) {
        this.isEditDotcor = true
        this.id = params.doctorInfo.id
        this.form.doctorName = params.doctorInfo.userName
        this.form.phone = params.doctorInfo.phone
        this.form.hospital = params.doctorInfo.hospitalName
        this.form.department = [params.doctorInfo.departmentId]
        this.serviceList = params.doctorInfo.serviceCityListSaveDtos
        this.serviceList.forEach(item => {
          item.onlineCityId = item.id
          item.name = item.serviceName
        })
        console.log(this.serviceList)
        this.form.serviceCity = [params.doctorInfo.serviceCityListSaveDtos[0].provinceId, params.doctorInfo.serviceCityListSaveDtos[0].cityId]
        console.log(params.doctorInfo)
        console.log(this.form.serviceList)
        this.form.groupName = params.doctorInfo.groupName
        this.form.groupManager = params.doctorInfo.groupManager
        this.form.staffWechatName = params.doctorInfo.wechatId
        this.form.groupMembers = params.doctorInfo.groupMembers
        this.form.wechatGroupId = params.doctorInfo.wechatGroupId
        /* this.$nextTick(() => {
          for (let i = 0; i < this.timeModel.serviceTime.length; i++) {
            this.$refs.DoctorTimeInterval[i].$data.timeForm.startTime = this.timeModel.serviceTime[i].startTime
            this.$refs.DoctorTimeInterval[i].$data.timeForm.endTime = this.timeModel.serviceTime[i].endTime
            this.$refs.DoctorTimeInterval[i].$data.timeForm.people = this.timeModel.serviceTime[i].people
          }
        })*/
      }
      // if (this.$route.params.id) {
      //   this.id = this.$route.params.id
      //   this.form.doctorName = this.$route.params.userName
      //   this.form.phone = this.$route.params.phone
      //   this.form.hospital = this.$route.params.hospitalName
      //   this.form.department = [this.$route.params.departmentId]
      //   this.serviceList = this.$route.params.serviceCityListSaveDtos
      //   this.serviceList.forEach(item => {
      //     item.onlineCityId = item.id
      //     item.name = item.serviceName
      //   })
      //   this.form.serviceCity = [this.$route.params.serviceCityListSaveDtos[0].provinceId, this.$route.params.serviceCityListSaveDtos[0].cityId]
      //   console.log(this.$route.params)
      //   console.log(this.form.serviceList)
      //   console.log(JSON.parse(this.$route.params.serviceTimeTemplate))
      //   this.form.timeModel = JSON.parse(this.$route.params.serviceTimeTemplate).id
      //   this.timeModel.id = JSON.parse(this.$route.params.serviceTimeTemplate).id
      //   this.timeModel.templateName = JSON.parse(this.$route.params.serviceTimeTemplate).templateName
      //   this.timeModel.appointmentDay = JSON.parse(this.$route.params.serviceTimeTemplate).appointmentDay
      //   this.timeModel.serviceTime = JSON.parse(JSON.parse(this.$route.params.serviceTimeTemplate).serviceTime)
      //   this.$nextTick(() => {
      //     for (let i = 0; i < this.timeModel.serviceTime.length; i++) {
      //       this.$refs.DoctorTimeInterval[i].$data.timeForm.startTime = this.timeModel.serviceTime[i].startTime
      //       this.$refs.DoctorTimeInterval[i].$data.timeForm.endTime = this.timeModel.serviceTime[i].endTime
      //       this.$refs.DoctorTimeInterval[i].$data.timeForm.people = this.timeModel.serviceTime[i].people
      //     }
      //   })
      // }
      const departmentData = {
        shopId: getShopID(),
        page: 1,
        limit: 0
      }
      getTwoLevelCityList(null).then(response => {
        this.serviceCityOptions = response.data.data
      })
      departmentList(departmentData).then(response => {
        console.log(response.data.data)
        const departmentList = response.data.data.data
        departmentList.forEach(item => {
          const label = {
            value: item.id,
            label: item.name
          }
          this.departmentOptions.push(label)
        })
      })

      /* const serviceCityData={
        shopId:''

      }*/
      /* this.form.doctorName=this.$route.query.doctorName
      this.form.hospital=this.$route.query.hospital
      this.form.phone=this.$route.query.phone
      this.form.department=this.$route.query.department
      this.form.serviceCity=this.$route.query.serviceCity
      this.form.serviceList=this.$route.query.serviceList
      this.form.timeModel=this.$route.query.timeModel
      this.timeform.day=this.$route.query.day
      this.timeform.startTime1=this.$route.query.startTime1
      this.timeform.endTime1=this.$route.query.endTime1
      this.timeform.num1=this.$route.query.num1
      this.timeform.startTime2=this.$route.query.startTime2
      this.timeform.endTime2=this.$route.query.endTime2
      this.timeform.num2=this.$route.query.num2*/
    },
    addModel() {
      this.$router.push('addServiceTime')
    },
    addServiceList() {
      if (!this.form.department || this.form.department.length == 0) {
        return this.$message({ type: 'error', message: '请先选择服务科室' })
      } else if (!this.form.serviceCity || this.form.serviceCity.length == 0) {
        return this.$message({ type: 'error', message: '请先选择服务城市' })
      } else if (this.form.serviceCity && this.form.serviceCity.length > 0 && this.form.department && this.form.department.length > 0) {
        this.dialogVisibleService = true
        this.getServiceList()
      }
    }, // 根据选择的服务城市id加载dialog 重新加载list
    resetService() {
      this.keywords = null
      this.getServiceList()
    },
    getServiceList() {
      const data = {
        /*        shopId: getShopID(),*/
        cityId: this.form.serviceCity[1],
        departmentId: this.form.department[0],
        page: this.pages.currentPage,
        limit: this.pages.pageSize,
        keywords: this.keywords
      }
      console.log(this.form.serviceCity[1])
      getServiceByCityId(data).then(response => {
        this.list = response.data.data.data
        this.pages.total = response.data.data.total
        console.log(this.pages.total)
      })
      // console.log(this.list)
    }, // 获取服务列表重新加载list

    /* selectModel() {
      this.dialogVisibleModel = true
      this.getTimeModelList()
    }, // 选择时间模板加载dialog 重新加载list
    getTimeModelList() {
      const data = {
        shopId: localStorage.getItem('shopId'),
        page: this.pages.currentPage,
        limit: this.pages.pageSize,
        keywords: this.keywords
      }
      console.log(data)
      getServiceTimeList(data).then(response => {
        console.log(response.data.data.data)
        this.list = response.data.data.data
        this.pages.total = response.data.data.total
      }).catch(() => {
        this.list = []
        this.pages.total = 0
      })
    }, // 获取时间模板列表重新加载list*/
    appendOnlineService() {
      this.$router.push({ name: 'addOnlineService' })
    },
    selectService(row) {
      if (this.serviceList && this.serviceList.length > 0) {
        const idList = this.serviceList.map(item => item.id)
        const id = row.id

        if (idList.indexOf(id) != -1) {
          return this.$message.warning('请勿选择相同的服务')
        } else {
          this.serviceList.push(row)
        }
      } else {
        this.serviceList.push(row)
      }
      console.log(this.serviceList)
      this.dialogVisibleService = false
    }, // 在dialog的选择服务加载到serviceList
    /* selectModelTime(row) {
      this.timeModel.id = row.id
      this.timeModel.templateName = row.templateName
      this.timeModel.appointmentDay = row.appointmentDay
      this.timeModel.serviceTime = JSON.parse(row.serviceTime)
      this.form.timeModel = row.id
      this.dialogVisibleModel = false
      this.$nextTick(() => {
        for (let i = 0; i < this.timeModel.serviceTime.length; i++) {
          this.$refs.DoctorTimeInterval[i].$data.timeForm.startTime = this.timeModel.serviceTime[i].startTime
          this.$refs.DoctorTimeInterval[i].$data.timeForm.endTime = this.timeModel.serviceTime[i].endTime
          this.$refs.DoctorTimeInterval[i].$data.timeForm.people = this.timeModel.serviceTime[i].people
        }
      })
    }, // 在dialog的选择模板加载到当前页面*/
    deleteService(index) {
      this.serviceList.splice(index, 1)
    }, // 删除服务
    // 分页操作
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
    deleteTimeInterval(index) {
      this.TimeIntervalList.splice(index, 1)
    },
    /** 提交新增医生*/
    submitDoctor() {
      /** 提交数据校验*/
      /* if (!this.form.doctorName) {
        return this.$message({ type: 'error', message: '医生名称不能为空' })
      }
      if (!this.form.phone) {
        return this.$message({ type: 'error', message: '手机号码不能为空' })
      }
      if (!this.form.hospital) {
        return this.$message({ type: 'error', message: '医院不能为空' })
      }
      if (this.form.department && this.form.department.length === 0) {
        return this.$message({ type: 'error', message: '科室不能为空' })
      }*/
      if (this.serviceList && this.form.department.length === 0) {
        return this.$message({ type: 'error', message: '服务不能为空' })
      }
      /* if (!this.form.timeModel
      ) {
        return this.$message({ type: 'error', message: '时间服务模板不能为空' })
      }*/
      this.$refs.doctorForm.validate(v => {
        if (v) {
          let serviceIdList = ''
          this.serviceList.forEach(item => {
            if (!serviceIdList) {
              serviceIdList = serviceIdList + item.onlineCityId
            } else {
              serviceIdList = serviceIdList + ',' + item.onlineCityId
            }
          })
          const data = {
            doctorName: this.form.doctorName,
            hospital: this.form.hospital,
            department: this.form.department[0],
            serviceId: serviceIdList,
            phone: this.form.phone,
            shopId: localStorage.getItem('shopId'),
            doctorId: this.id,
            groupName: this.form.groupName,
            groupManager: this.form.groupManager,
            staffWechatName: this.form.staffWechatName,
            groupMembers: this.form.groupMembers,
            wechatGroupId: this.form.wechatGroupId
          }
          console.log(data)
          /* console.log(this.form.serviceCity)*/
          const loadingInstance = Loading.service({ fullscreen: true })
          addDoctor(data).then(response => {
            loadingInstance.close()
            if (this.isEditDotcor) {
              this.$message({
                type: 'success',
                message: '编辑成功'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            } else {
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            }
          }).catch(res => {
            loadingInstance.close()
            if (res && res.data && res.data.errno !== 0) {
              this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.addDoctor {
  padding: 0px 100px;
  .ele-title {
    margin-top: 40px;
    padding-left: 20px;
  }
  .ele-con-res {
    background: #f3f3f3;
    height: 50px;
    border-radius: 5px;
    line-height: 50px;
    margin-top: 40px;
    span {
      font-size: 16px;
      font-weight: bold;
      padding-left: 20px;
    }
  }
  .ele-content {
    padding: 0px 25px;
    ::v-deep.el-form-item--medium {
      margin-top: 20px;
    }
    ::v-deep.el-form-item__label {
      width: 100px;
      text-align: start;
    }
    .ele-proportion,
    .ele-pre {
      margin-left: 100px;
    }
    .ele-pre {
      line-height: 30px;
      font-size: 14px;
      color: gray;
      width: 520px;
    }
    .title-txt {
      font-size: 14px;
      color: gray;
      white-space: nowrap;
      margin: 0;
      padding: 0;
    }
    .service-head {
      background: #f3f3f3;
    }
    .timeModelBox {
      .line{
        margin-left: 38px;
        height: 36px;
        line-height: 36px;
        text-align: center;
      }
    }
  }
  .ele-div-keysearch {
    display: flex;
    justify-content: space-between;
    .search-left {
      display: flex;
      ::v-deep.el-select,
      .ele-input,
      .el-button {
        margin-left: 15px;
      }
      ::v-deep.el-select {
        width: 100px;
      }
    }
    .search-flex {
      display: flex;
      ::v-deep.el-button {
        margin-left: 15px;
      }
    }
  }
  .ele-table {
    width: 100%;
    margin-top: 40px;
    .ele-div-footer {
      display: flex;
      justify-content: space-between;
      margin: 50px 0px 100px 0px;
      .footer-left {
        ::v-deep.el-button {
          width: 100px;
          margin: 0px;
        }
      }
    }
  }
}
.flex {
  display: flex;
}
.marginleft {
  margin-left: 12px;
}
.text {
  text-align: end;
  padding-right: 10px;
}
</style>
